use sqlx::{types::Decimal, Row};
use num_traits::cast::ToPrimitive;
use shq_common::prelude::{divi_map::{DiviType, EmplDivis, EmplDivisCache}, get_ch_pool, mysql};
pub async fn comp_divi_new_cb(tx: &mut sqlx::Transaction<'_, sqlx::MySql>,run_id:u64, user_id:u32) -> anyhow::Result<()> {
    let bdate=mysql::get_back_date().await?;
	let bdate_str=bdate.format("%Y-%m-%d").to_string();
	let tx: &mut sqlx::MySqlConnection=tx;
	for i in 1..=3 {
	    let sql=format!(r#"INSERT INTO comp_acco_divi(acid,emid,dsvl,dsdt,dsem,opdt)
		SELECT acid,emid{i} emid,dsvl{i}/100 dsvl,CASE WHEN opdt < '{bdate_str}' THEN '{bdate_str}' ELSE opdt END dsdt,{user_id} dsem,now() opdt
		FROM comp_acco_divi_flow_new
		WHERE frid={run_id} AND dsvl{i}>0 and emid{i}>0"#);
		sqlx::query(sql.as_str()).execute(&mut *tx).await?;
	}
	let sql= "select acid,emid1,dsvl1,emid2,dsvl2,emid3,dsvl3 from comp_acco_divi_flow_new where FRID=?";
	let row=sqlx::query(sql).bind(&run_id).fetch_one(&mut *tx).await?;
	let acid:u64=row.try_get("acid")?;
	let emid1:u32=row.try_get("emid1")?;
	let dsvl1:Decimal=row.try_get("dsvl1")?;
	let emid2:Option<u32>=row.try_get("emid2")?;
	let dsvl2:Option<Decimal>=row.try_get("dsvl2")?;
	let emid3:Option<u32>=row.try_get("emid3")?;
	let dsvl3:Option<Decimal>=row.try_get("dsvl3")?;
	let mut empl_divis=EmplDivis::new();
	empl_divis.add(emid1, dsvl1.to_f64().ok_or(anyhow::anyhow!("dsvl1 to f64 error"))?);
	if let Some(emid2)=emid2 {
		if let Some(dsvl2)=dsvl2 {
			empl_divis.add(emid2, dsvl2.to_f64().ok_or(anyhow::anyhow!("dsvl2 to f64 error"))?);
		}
	}
	if let Some(emid3)=emid3 {
		if let Some(dsvl3)=dsvl3 {
			empl_divis.add(emid3, dsvl3.to_f64().ok_or(anyhow::anyhow!("dsvl3 to f64 error"))?);
		}
	}
	let mut edc=EmplDivisCache::new()?;
	edc.set(DiviType::Comp, acid, empl_divis)?;
	let sql= format!("INSERT INTO JOIN_COMP_ACCO_ISDIVI(ACID,ISRD) SELECT {} ACID,1 ISRD",acid);
	let mut client=get_ch_pool().get_handle().await?;
	client.execute(sql.as_str()).await?;
	Ok(())
}

